﻿using System;
using System.Web.UI.WebControls;

namespace UDS.Web.UI.Controls
{
    public abstract class EnumDropDownList : DropDownList
    {
        /// <summary>
        /// Gets the type of the underlying enum type.
        /// </summary>
        protected abstract Type EnumType
        {
            get;
        }

        /// <summary>
        /// Gets the value of the selected item.
        /// </summary>
        protected virtual int DefaultEnumValue
        {
            get { return -1; }
        }

        /// <summary>
        /// Indicates whehter to display <see cref="DisplayNameAttribute.Name"/> or <see cref="DisplayNameAttribute.Description"/>
        /// </summary>
        protected virtual bool ShowDisplayName
        {
            get { return true; }
        }

        /// <summary>
        /// Gets the selected enum value.
        /// </summary>
        protected int SelectedEnumValue
        {
            get { return int.Parse(SelectedValue); }
            set
            {
                ClearSelection();
                var listItem = Items.FindByValue(value.ToString());
                if (listItem != null)
                {
                    listItem.Selected = true;
                }
            }
        }

        /// <summary>
        /// Initialize list items.
        /// </summary>
        protected override void OnInit(EventArgs e)
        {
            var type = EnumType;
            if (type == null || !type.IsEnum)
            {
                throw new InvalidOperationException("EnumType must be an enum type.");
            }

            var map = Utility.GetEnumDisplayNames(type);
            var selectedValue = DefaultEnumValue;
            foreach (var kvp in map)
            {
                var listItem = new ListItem();
                listItem.Value = kvp.Key.ToString();
                listItem.Text = ShowDisplayName ? kvp.Value.Name : kvp.Value.Description;
                listItem.Selected = (selectedValue == kvp.Key);

                Items.Add(listItem);
            }

            base.OnInit(e);
        }
    }
}
